#include <bits/stdc++.h>
using namespace std;
int n, m;
int pos[500*500+10], A[500+10][500+10], ans[500+10][500+10];
int main() {
    ios::sync_with_stdio(false);cin.tie(nullptr);
    int T; cin >> T;
    while (T--){
        cin >> n >> m;
        set<int> col;
        for (int i = 0; i < n; ++i) {
            int f; cin >> f;
            col.insert(f);
            pos[f] = i;
            A[i][0] = f;
            for (int j = 1; j < m; ++j) {
                cin >> A[i][j];
            }
        }
        int C[500+10], tC[500+10];
        for (int c = 0; c < m; ++c) {
            bool isf = true;
            for (int r = 0; r < n; ++r) {
                cin >> tC[r];
                if(!col.count(tC[r])) isf = false;
            }
            if(isf){
                memcpy(C, tC, sizeof C);
            }
        }
        for (int r = 0; r < n; ++r) {
            int f = C[r];
            int rr = pos[f];
            for (int c = 0; c < m; ++c) {
                if(c) cout << ' ';
                cout << A[rr][c];
            }
            cout << "\n";
        }
    }
    return 0;
}